<?php

/*
=====================================================
 FluxBB - Delux Board Converstations (DBC)
-----------------------------------------------------
 http://dbc-forum.com/
 http://fluxbb.org/
-----------------------------------------------------
 Copyright (c) 2010,2011 FluxBB - Delux Board Conversations (DBC)
-----------------------------------------------------
 Предсловие: Данный скрипт (DBC) не является работой с нуля, то 
 есть ядром скрипта всё также остаётся FuxBB,но теперь в оболочке
 DBC.
=====================================================
*/

define('DBC_ROOT', './');
define('DBC_SEARCH', 1);
require DBC_ROOT.'engine/common.php';

// Load the search.php language file
require DBC_ROOT.'language/'.$DBC_user['language'].'/search.php';
require DBC_ROOT.'language/'.$DBC_user['language'].'/forum.php';


if ($DBC_user['g_read_board'] == '0')
	message($lang_common['No view']);
else if ($DBC_user['g_search'] == '0')
	message($lang_search['No search permission']);

require DBC_ROOT.'engine/search_idx.php';

// Figure out what to do :-)
if (isset($_GET['action']) || isset($_GET['search_id']))
{
	$action = (isset($_GET['action'])) ? $_GET['action'] : null;
	$forum = (isset($_GET['forum'])) ? intval($_GET['forum']) : -1;
	$sort_dir = (isset($_GET['sort_dir']) && $_GET['sort_dir'] == 'DESC') ? 'DESC' : 'ASC';

	// If a search_id was supplied
	if (isset($_GET['search_id']))
	{
		$search_id = intval($_GET['search_id']);
		if ($search_id < 1)
			message($lang_common['Bad request']);
			$sword = (isset($_GET['words'])) ? strtolower(trim($_GET['words'])) : null;	
	}
	// If it's a regular search (keywords and/or author)
	else if ($action == 'search')
	{
		$keywords = (isset($_GET['keywords'])) ? utf8_strtolower(DBC_trim($_GET['keywords'])) : null;
		$author = (isset($_GET['author'])) ? utf8_strtolower(DBC_trim($_GET['author'])) : null;

		if (preg_match('#^[\*%]+$#', $keywords) || (DBC_strlen(str_replace(array('*', '%'), '', $keywords)) < DBC_SEARCH_MIN_WORD && !is_cjk($keywords)))
			$keywords = '';

		if (preg_match('#^[\*%]+$#', $author) || DBC_strlen(str_replace(array('*', '%'), '', $author)) < 2)
			$author = '';

		if (!$keywords && !$author)
			message($lang_search['No terms']);

		if ($author)
			$author = str_replace('*', '%', $author);

		$show_as = (isset($_GET['show_as'])) ? $_GET['show_as'] : 'posts';
		$sort_by = (isset($_GET['sort_by'])) ? intval($_GET['sort_by']) : null;
		$search_in = (!isset($_GET['search_in']) || $_GET['search_in'] == 'all') ? 0 : (($_GET['search_in'] == 'message') ? 1 : -1);
	}
	// If it's a user search (by ID)
	else if ($action == 'show_user')
	{
		$user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0;
		if ($user_id < 2)
			message($lang_common['Bad request']);
	}
	// MOD warnings - Visman
	else if ($action == 'show_user_warn')
	{
		if ($DBC_user['is_guest'])
			message($lang_common['No permission']);

		$user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : $DBC_user['id'];
		if ($user_id < 2)
			message($lang_common['Bad request']);
	}
	else
	{
		if ($action != 'show_new' && $action != 'show_24h' && $action != 'show_unanswered' && $action != 'show_subscriptions')
			message($lang_common['Bad request']);
	}


	// If a valid search_id was supplied we attempt to fetch the search results from the db
	if (isset($search_id))
	{
		$ident = ($DBC_user['is_guest']) ? get_remote_address() : $DBC_user['username'];

		$result = $db->query('SELECT search_data FROM '.$db->prefix.'search_cache WHERE id='.$search_id.' AND ident=\''.$db->escape($ident).'\'') or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());
		if ($row = $db->fetch_assoc($result))
		{
			$temp = unserialize($row['search_data']);

			$search_ids = unserialize($temp['search_ids']);
			$num_hits = $temp['num_hits'];
			$sort_by = $temp['sort_by'];
			$sort_dir = $temp['sort_dir'];
			$show_as = $temp['show_as'];

			unset($temp);
		}
		else
			message($lang_search['No hits']);
	}
	else
	{
		$keyword_results = $author_results = array();

		// Search a specific forum?
		$forum_sql = ($forum != -1 || ($forum == -1 && $DBC_config['o_search_all_forums'] == '0' && !$DBC_user['is_admmod'])) ? ' AND t.forum_id = '.$forum : '';

		if (!empty($author) || !empty($keywords))
		{
			// Flood protection
			if ($DBC_user['last_search'] && (time() - $DBC_user['last_search']) < $DBC_user['g_search_flood'] && (time() - $DBC_user['last_search']) >= 0)
				message(sprintf($lang_search['Search flood'], $DBC_user['g_search_flood']));

			if (!$DBC_user['is_guest'])
				$db->query('UPDATE '.$db->prefix.'users SET last_search='.time().' WHERE id='.$DBC_user['id']) or error('Unable to update user', __FILE__, __LINE__, $db->error());
			else
				$db->query('UPDATE '.$db->prefix.'online SET last_search='.time().' WHERE ident=\''.$db->escape(get_remote_address()).'\'' ) or error('Unable to update user', __FILE__, __LINE__, $db->error());

			switch ($sort_by)
			{
				case 1:
					$sort_by_sql = ($show_as == 'topics') ? 't.poster' : 'p.poster';
					$sort_type = SORT_STRING;
					break;

				case 2:
					$sort_by_sql = 't.subject';
					$sort_type = SORT_STRING;
					break;

				case 3:
					$sort_by_sql = 't.forum_id';
					$sort_type = SORT_NUMERIC;
					break;

				case 4:
					$sort_by_sql = 't.last_post';
					$sort_type = SORT_NUMERIC;
					break;

				default:
					$sort_by_sql = ($show_as == 'topics') ? 't.last_post' : 'p.posted';
					$sort_type = SORT_NUMERIC;
					break;
			}

			// If it's a search for keywords
			if ($keywords)
			{
				// split the keywords into words
				$keywords_array = split_words($keywords, false);

				if (empty($keywords_array))
					message($lang_search['No hits']);

				// Should we search in message body or topic subject specifically?
				$search_in_cond = ($search_in) ? (($search_in > 0) ? ' AND m.subject_match = 0' : ' AND m.subject_match = 1') : '';

				$word_count = 0;
				$match_type = 'and';

				$sort_data = array();
				foreach ($keywords_array as $cur_word)
				{
					switch ($cur_word)
					{
						case 'and':
						case 'or':
						case 'not':
							$match_type = $cur_word;
							break;

						default:
						{
							if (is_cjk($cur_word))
							{
								$where_cond = str_replace('*', '%', $cur_word);
								$where_cond = ($search_in ? (($search_in > 0) ? 'p.message LIKE \'%'.$db->escape($where_cond).'%\'' : 't.subject LIKE \'%'.$db->escape($where_cond).'%\'') : 'p.message LIKE \'%'.$db->escape($where_cond).'%\' OR t.subject LIKE \'%'.$db->escape($where_cond).'%\'');

								$result = $db->query('SELECT p.id AS post_id, p.topic_id, '.$sort_by_sql.' AS sort_by FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE ('.$where_cond.')'.$dop_where.' AND (fp.read_forum IS NULL OR fp.read_forum=1)'.$forum_sql, true) or error('Unable to search for posts', __FILE__, __LINE__, $db->error());
							}
							else
								$result = $db->query('SELECT m.post_id, p.topic_id, '.$sort_by_sql.' AS sort_by FROM '.$db->prefix.'search_words AS w INNER JOIN '.$db->prefix.'search_matches AS m ON m.word_id = w.id INNER JOIN '.$db->prefix.'posts AS p ON p.id=m.post_id INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE w.word LIKE \''.$db->escape(str_replace('*', '%', $cur_word)).'\''.$search_in_cond.$dop_where.' AND (fp.read_forum IS NULL OR fp.read_forum=1)'.$forum_sql, true) or error('Unable to search for posts', __FILE__, __LINE__, $db->error());

							$row = array();
							while ($temp = $db->fetch_assoc($result))
							{
								$row[$temp['post_id']] = $temp['topic_id'];

								if (!$word_count)
								{
									$keyword_results[$temp['post_id']] = $temp['topic_id'];
									$sort_data[$temp['post_id']] = $temp['sort_by'];
								}
								else if ($match_type == 'or')
								{
									$keyword_results[$temp['post_id']] = $temp['topic_id'];
									$sort_data[$temp['post_id']] = $temp['sort_by'];
								}
								else if ($match_type == 'not')
								{
									unset($keyword_results[$temp['post_id']]);
									unset($sort_data[$temp['post_id']]);
								}
							}

							if ($match_type == 'and' && $word_count)
							{
								foreach ($keyword_results as $post_id => $topic_id)
								{
									if (!isset($row[$post_id]))
									{
										unset($keyword_results[$post_id]);
										unset($sort_data[$post_id]);
									}
								}
							}

							++$word_count;
							$db->free_result($result);

							break;
						}
					}
				}

				// Sort the results - annoyingly array_multisort re-indexes arrays with numeric keys, so we need to split the keys out into a seperate array then combine them again after
				$post_ids = array_keys($keyword_results);
				$topic_ids = array_values($keyword_results);

				array_multisort(array_values($sort_data), $sort_dir == 'DESC' ? SORT_DESC : SORT_ASC, $sort_type, $post_ids, $topic_ids);

				// combine the arrays back into a key=>value array (array_combine is PHP5 only unfortunately)
				$num_results = count($keyword_results);
				$keyword_results = array();
				for ($i = 0;$i < $num_results;$i++)
					$keyword_results[$post_ids[$i]] = $topic_ids[$i];

				unset($sort_data, $post_ids, $topic_ids);
			}

			// If it's a search for author name (and that author name isn't Guest)
			if ($author && $author != 'guest' && $author != utf8_strtolower($lang_common['Guest']))
			{
				switch ($db_type)
				{
					case 'pgsql':
						$result = $db->query('SELECT id FROM '.$db->prefix.'users WHERE username ILIKE \''.$db->escape($author).'\'') or error('Unable to fetch users', __FILE__, __LINE__, $db->error());
						break;

					default:
						$result = $db->query('SELECT id FROM '.$db->prefix.'users WHERE username LIKE \''.$db->escape($author).'\'') or error('Unable to fetch users', __FILE__, __LINE__, $db->error());
						break;
				}

				if ($db->num_rows($result))
				{
					$user_ids = array();
					while ($row = $db->fetch_row($result))
						$user_ids[] = $row[0];

					$result = $db->query('SELECT p.id AS post_id, p.topic_id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.poster_id IN('.implode(',', $user_ids).')'.$forum_sql.' ORDER BY '.$sort_by_sql.' '.$sort_dir) or error('Unable to fetch matched posts list', __FILE__, __LINE__, $db->error());
					while ($temp = $db->fetch_assoc($result))
						$author_results[$temp['post_id']] = $temp['topic_id'];

					$db->free_result($result);
				}
			}

			// If we searched for both keywords and author name we want the intersection between the results
			if ($author && $keywords)
				$search_ids = array_intersect_assoc($keyword_results, $author_results);
			else if ($keywords)
				$search_ids = $keyword_results;
			else
				$search_ids = $author_results;

			unset($keyword_results, $author_results);

			if ($show_as == 'topics')
				$search_ids = array_values($search_ids);
			else
				$search_ids = array_keys($search_ids);

			$search_ids = array_unique($search_ids);

			$num_hits = count($search_ids);
			if (!$num_hits)
				message($lang_search['No hits']);
		}
		else if ($action == 'show_new' || $action == 'show_24h' || $action == 'show_user' || $action == 'show_subscriptions' || $action == 'show_unanswered')
		{
			// If it's a search for new posts
			if ($action == 'show_new')
			{
				if ($DBC_user['is_guest'])
					message($lang_common['No permission']);

				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.last_post>'.$DBC_user['last_visit'].' AND t.moved_to IS NULL'.(isset($_GET['fid']) ? ' AND t.forum_id='.intval($_GET['fid']) : '').' ORDER BY t.last_post DESC') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
				$num_hits = $db->num_rows($result);

				if (!$num_hits)
					message($lang_search['No new posts']);
			}
			// If it's a search for todays posts
			else if ($action == 'show_24h')
			{
				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.last_post>'.(time() - 86400).' AND t.moved_to IS NULL ORDER BY t.last_post DESC') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
				$num_hits = $db->num_rows($result);

				if (!$num_hits)
					message($lang_search['No recent posts']);
			}
			// If it's a search for posts by a specific user ID
			else if ($action == 'show_user')
			{
				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'posts AS p ON t.id=p.topic_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.poster_id='.$user_id.' GROUP BY t.id'.($db_type == 'pgsql' ? ', t.last_post' : '').' ORDER BY t.last_post DESC') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
				$num_hits = $db->num_rows($result);

				if (!$num_hits)
					message($lang_search['No user posts']);
			}
			// If it's a search for subscribed topics
			else if ($action == 'show_subscriptions')
			{
				if ($DBC_user['is_guest'])
					message($lang_common['Bad request']);


				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'subscriptions AS s ON (t.id=s.topic_id AND s.user_id='.$DBC_user['id'].') LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) ORDER BY t.last_post DESC') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
				$num_hits = $db->num_rows($result);

				if (!$num_hits)
					message($lang_search['No subscriptions']);
			}
			// If it's a search for unanswered posts
			else
			{
				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.num_replies=0 AND t.moved_to IS NULL ORDER BY t.last_post DESC') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
				$num_hits = $db->num_rows($result);

				if (!$num_hits)
					message($lang_search['No unanswered']);
			}

			// We want to sort things after last post
			$sort_by = 4;
			$sort_dir = 'DESC';

			$search_ids = array();
			while ($row = $db->fetch_row($result))
				$search_ids[] = $row[0];

			$db->free_result($result);

			$show_as = 'topics';
		}
		// MOD warnings - Visman
		else if ($action == 'show_user_warn')
		{
			$sort_by = 9;
			$show_as = 'posts';
			$sort_dir = 'DESC';

			$result = $db->query('SELECT p.id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'warnings AS w ON w.id=p.id INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=t.forum_id AND fp.group_id='.$DBC_user['g_id'].') WHERE p.poster_id='.$user_id.' AND (fp.read_forum IS NULL OR fp.read_forum=1) ORDER BY w.posted DESC', true) or error('Unable to search for posts', __FILE__, __LINE__, $db->error());
			$num_hits = $db->num_rows($result);

			if (!$num_hits)
				message($lang_search['No user posts']);

			$search_ids = array();
			while ($row = $db->fetch_row($result))
				$search_ids[] = $row[0];

			$db->free_result($result);
		}
		else
			message($lang_common['Bad request']);


		// Prune "old" search results
//		$old_searches = array();
//		$result = $db->query('SELECT ident FROM '.$db->prefix.'online') or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());
//
//		if ($db->num_rows($result))
//		{
//			while ($row = $db->fetch_row($result))
//				$old_searches[] = '\''.$db->escape($row[0]).'\'';       implode(',', $old_searches)
		if ($online_search != '')
			$db->query('DELETE FROM '.$db->prefix.'search_cache WHERE ident NOT IN('.substr($online_search, 1).')') or error('Unable to delete search results', __FILE__, __LINE__, $db->error());
//		}

		// Fill an array with our results and search properties
		$temp = serialize(array(
			'search_ids'		=> serialize($search_ids),
			'num_hits'			=> $num_hits,
			'sort_by'			=> $sort_by,
			'sort_dir'			=> $sort_dir,
			'show_as'			=> $show_as,
		));
		$search_id = mt_rand(1, 2147483647);

		$ident = ($DBC_user['is_guest']) ? get_remote_address() : $DBC_user['username'];

		$db->query('INSERT INTO '.$db->prefix.'search_cache (id, ident, search_data) VALUES('.$search_id.', \''.$db->escape($ident).'\', \''.$db->escape($temp).'\')') or error('Unable to insert search results', __FILE__, __LINE__, $db->error());

		if ($action != 'show_new' && $action != 'show_24h')
		{
			$db->end_transaction();
			$db->close();

			// Redirect the user to the cached result page
			header('Location: search/'.$search_id.'&words='.implode("-",$keywords_array));
			exit;
		}
	}


	// Fetch results to display
	if (!empty($search_ids))
	{
		switch ($sort_by)
		{
			case 1:
				$sort_by_sql = ($show_as == 'topics') ? 't.poster' : 'p.poster';
				break;

			case 2:
				$sort_by_sql = 't.subject';
				break;

			case 3:
				$sort_by_sql = 't.forum_id';
				break;

			case 4:
				$sort_by_sql = 't.last_post';
				break;

			case 9:                        // MOD warnings - Visman
				$sort_by_sql = 'w.posted';
				break;

			default:
				$sort_by_sql = ($show_as == 'topics') ? 't.last_post' : 'p.posted';
				break;
		}

		// Determine the topic or post offset (based on $_GET['p'])
		$per_page = ($show_as == 'posts') ? $DBC_user['disp_posts'] : $DBC_user['disp_topics'];
		$num_pages = ceil($num_hits / $per_page);

		$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : intval($_GET['p']);
		$start_from = $per_page * ($p - 1);

		// Generate paging links
		$paging_links = '<span class="pages-label">'.$lang_common['Pages'].' </span>'.paginate($num_pages, $p, 'search/'.$search_id);

		// throw away the first $start_from of $search_ids, only keep the top $per_page of $search_ids
		$search_ids = array_slice($search_ids, $start_from, $per_page);

		$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $lang_search['Search results']);
		define('DBC_ACTIVE_PAGE', 'search');
		require DBC_ROOT.'engine/engine.php';


?>




<div class="linkst">
		<p class="pagelink"><span class="contacts"><?php echo $paging_links ?></span></p>
		<div class="clearer"></div>
</div><br/>


<br/><table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="28" class="bg_forum_title_left"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $lang_search['Search results'] ?></span></td>
<td align="center" width="28" class="bg_forum_title_right"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
</tr></table>

<?php

		if ($show_as == 'topics')
		{
			$topic_count = 0;

?>
			<table height="17" style="height: 17px;" cellpadding="0" cellspacing="0" border="1" class="bg_forum_r cClass blocktable">

			<thead>
				<tr>
					<td class="tcl" class="bg_forum_r" scope="col"><?php echo $lang_common['Topic'] ?></td>
					<td class="tc2" class="bg_forum_r" scope="col"><?php echo $lang_common['Forum'] ?></td>
					<td class="tc3" class="bg_forum_r" scope="col"><?php echo $lang_common['Replies'] ?></td>
					<td class="tcr" class="bg_forum_r" scope="col"><?php echo $lang_common['Last post'] ?></td>
				</tr>
			</thead>
			</table>



<div id="vf">
	<div class="box">
		<div class="inbox">
			<table cellspacing="0" class="block_table_b cClass blocktable bg_forum_td" border="">
			<tbody>
<?php

		}
		else if ($show_as == 'posts')
		{
			require DBC_ROOT.'language/'.$DBC_user['language'].'/topic.php';

			require DBC_ROOT.'engine/parser.php';

			$post_count = 0;
		}

		// Get topic/forum tracking data
		if (!$DBC_user['is_guest'])
			$tracked_topics = get_tracked_topics();

//			$result = $db->query('SELECT p.id AS pid, p.poster AS pposter, p.posted AS pposted, p.poster_id, p.message, p.hide_smilies, t.id AS tid, t.poster, t.subject, t.first_post_id, t.last_post, t.last_post_id, t.last_poster, t.num_replies, t.forum_id, f.forum_name FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id WHERE p.id IN('.implode(',', $search_ids).') ORDER BY '.$sort_by_sql.' '.$sort_dir) or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());
		if ($show_as == 'posts')
			$result = $db->query('SELECT p.id AS pid, p.poster AS pposter, p.posted AS pposted, p.poster_id, p.message, p.hide_smilies, t.id AS tid, t.poster, t.subject, t.first_post_id, t.last_post, t.last_post_id, t.last_poster, t.num_replies, t.forum_id, f.forum_name, w.message AS wmessage, w.poster AS wposter, w.posted AS wposted FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'warnings AS w ON w.id=p.id WHERE p.id IN('.implode(',', $search_ids).') ORDER BY '.$sort_by_sql.' '.$sort_dir) or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());
		else
			$result = $db->query('SELECT t.id AS tid, t.poster, t.subject, t.last_post, t.last_post_id, t.last_poster, t.num_replies, t.closed, t.sticky, t.forum_id, f.forum_name FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id WHERE t.id IN('.implode(',', $search_ids).') ORDER BY '.$sort_by_sql.' '.$sort_dir) or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());

		while ($cur_search = $db->fetch_assoc($result))
		{
			$forum = '<a href="'.$DBC_config['o_base_url'].'/topic_'.$cur_search['forum_id'].'">'.DBC_htmlspecialchars($cur_search['forum_name']).'</a>';

			if ($DBC_config['o_censoring'] == '1')
				$cur_search['subject'] = censor_words($cur_search['subject']);

			if ($show_as == 'posts')
			{
				++$post_count;
				$icon_type = 'icon';

				if (!$DBC_user['is_guest'] && $cur_search['last_post'] > $DBC_user['last_visit'] && (!isset($tracked_topics['topics'][$cur_search['tid']]) || $tracked_topics['topics'][$cur_search['tid']] < $cur_search['last_post']) && (!isset($tracked_topics['forums'][$cur_search['forum_id']]) || $tracked_topics['forums'][$cur_search['forum_id']] < $cur_search['last_post']))
				{
					$item_status = 'inew';
					$icon_type = 'icon icon-new';
					$icon_text = $lang_topic['New icon'];
				}
				else
				{
					$item_status = '';
					$icon_text = '<!-- -->';
				}

				if ($DBC_config['o_censoring'] == '1')
					$cur_search['message'] = censor_words($cur_search['message']);
					require DBC_ROOT.'language/'.$DBC_user['language'].'/topic.php';
				
					$search_set[$i]['message'] = preg_replace('#\[hide\](.*?)\[/hide\]#s',$lang_topic['Hidden text'],$search_set[$i]['message']);
					$search_set[$i]['message'] = preg_replace('#\[hide\](.*?)$#s',$lang_topic['Hidden text'],$search_set[$i]['message']);

				$message = parse_message($cur_search['message'], $cur_search['hide_smilies']);
				$pposter = DBC_htmlspecialchars($cur_search['pposter']);

				if ($cur_search['poster_id'] > 1)
				{
					if ($DBC_user['g_view_users'] == '1')
						$pposter = '<strong><a href="'.$DBC_config['o_base_url'].'/user_'.$cur_search['poster_id'].'">'.$pposter.'</a></strong>';
					else
						$pposter = '<strong>'.$pposter.'</strong>';
				}

				if (!empty($cur_search['wposter']))
				$warnings = '<cite>'.format_time($cur_search['wposted']).' '.DBC_htmlspecialchars($cur_search['wposter']).' '.$lang_common['wrote'].'</cite>'.parse_message($cur_search['wmessage'], false).'';

?>







<table border="0" cellpadding="0" cellspacing="0" width="100%"><thead><tr>
<td class="blockpost_t" align="center" width="217"><span style="font-family: Tahoma;"><?php echo $pposter ?></span></td>
<td class="blockpost_t" style="padding: 0px 5px 0px 5px; font-size: 11px;color: #1d83b8;" align="left">



<table border="0" cellpadding="0" cellspacing="0" width="100%"><thead><tr>
<td align="left" width="50%">


	<?php if ($cur_search['pid'] != $cur_search['first_post_id']) echo $lang_topic['Re'].' ' ?><?php echo $forum ?>  »&#160;<a href="<?php echo $DBC_config['o_base_url'] ?>/topic_<?php echo $cur_search['tid'] ?>"><?php echo DBC_htmlspecialchars($cur_search['subject']) ?></a>


</td>
<td align="right" width="50%"><span class="conr">#<?php echo ($start_from + $post_count) ?></span></td>
</tr></thead></table>


</td>
</tr></thead></table>

<table border="0" cellpadding="0" cellspacing="0" height="24" width="100%"><thead><tr>
<td style="background: #ffffff;border: 1px solid #CAD7E1;border-top: 0px;border-bottom: 0px;padding: 5px; font-size: 11px;" align="left" valign="top" width="207">

				<span><?php echo $lang_topic['Replies'].' '.forum_number_format($cur_search['num_replies']) ?></span><br/>
				<span><?php echo $lang_topic['Date'].' '.format_time($cur_search['pposted']) ?></span><br/>
								

</td>
<td style="background: #fcfdfe;border: 1px solid #CAD7E1;padding: 2px 5px 5px 5px;border-top: 0px;border-bottom: 0px;" align="left" valign="top">
					<div class="postmsg">
						<?php echo $message."\n" ?>
					</div>
<?php if (!empty($cur_search['wposter'])): ?>
					<div class="postwarn">
						<?php echo $warnings."\n" ?>
					</div>
<?php endif; ?>
				<div class="clearer"></div>


<div align="right">
	<div class="inbox">
			<div class="postfoot clearb">
				<div class="postfootright">
					<ul>
						<li><span><a href="<?php echo $DBC_config['o_base_url'] ?>/topic_<?php echo $cur_search['tid'] ?>"><?php echo $lang_search['Go to topic'] ?></a></span></li>
						<li><span><a href="<?php echo $DBC_config['o_base_url'] ?>/topics_<?php echo $cur_search['pid'].'#p'.$cur_search['pid'] ?>"><?php echo $lang_search['Go to post'] ?></a></span></li>
					</ul>
				</div>
			</div>
		</div>
</div>

</td>
</tr></thead></table>











<?php

			}
			else
			{
				++$topic_count;
				$status_text = array();
				$item_status = ($topic_count % 2 == 0) ? 'roweven' : 'rowodd';
				$icon_type = 'icon';

				$subject = '<a href="'.$DBC_config['o_base_url'].'/topic_'.$cur_search['tid'].'">'.DBC_htmlspecialchars($cur_search['subject']).'</a> <span class="byuser">'.$lang_common['by'].' '.DBC_htmlspecialchars($cur_search['poster']).'</span>';

				if ($cur_search['sticky'] == '1')
				{
					$item_status .= ' isticky';
					$status_text[] = '<span class="stickytext">'.$lang_forum['Sticky'].'</span>';
				}

				if ($cur_search['closed'] != '0')
				{
					$status_text[] = '<span class="closedtext">'.$lang_forum['Closed'].'</span>';
					$item_status .= ' iclosed';
				}

				if (!$DBC_user['is_guest'] && $cur_search['last_post'] > $DBC_user['last_visit'] && (!isset($tracked_topics['topics'][$cur_search['tid']]) || $tracked_topics['topics'][$cur_search['tid']] < $cur_search['last_post']) && (!isset($tracked_topics['forums'][$cur_search['forum_id']]) || $tracked_topics['forums'][$cur_search['forum_id']] < $cur_search['last_post']))
				{
					$item_status .= ' inew';
					$icon_type = 'icon icon-new';
					$subject = '<strong>'.$subject.'</strong>';
					$subject_new_posts = '<span class="newtext">[ <a href="'.$DBC_config['o_base_url'].'/topic_'.$cur_search['tid'].'&amp;action=new" title="'.$lang_common['New posts info'].'">'.$lang_common['New posts'].'</a> ]</span>';
				}
				else
					$subject_new_posts = null;

				// Insert the status text before the subject
				$subject = implode(' ', $status_text).' '.$subject;

				$num_pages_topic = ceil(($cur_search['num_replies'] + 1) / $DBC_user['disp_posts']);

				if ($num_pages_topic > 1)
					$subject_multipage = '<span class="pagestext">[ '.paginate($num_pages_topic, -1, 'viewtopic.php?id='.$cur_search['tid']).' ]</span>';
				else
					$subject_multipage = null;

				// Should we show the "New posts" and/or the multipage links?
				if (!empty($subject_new_posts) || !empty($subject_multipage))
				{
					$subject .= !empty($subject_new_posts) ? ' '.$subject_new_posts : '';
					$subject .= !empty($subject_multipage) ? ' '.$subject_multipage : '';
				}

?>
				<tr class="<?php echo $item_status ?>">
					<td class="tcl">
						<div class="<?php echo $icon_type ?>"><div class="nosize"><?php echo forum_number_format($topic_count + $start_from) ?></div></div>
						<div class="tclcon">
							<div>
								<?php echo $subject."\n" ?>
							</div>
						</div>
					</td>
					<td class="tc3"><?php echo $forum ?></td>
					<td class="tc3"><?php echo forum_number_format($cur_search['num_replies']) ?></td>
					<td class="tcr"><?php echo '<a href="'.$DBC_config['o_base_url'].'/topics_'.$cur_search['last_post_id'].'&amp;words='.$sword.'#p'.$cur_search['last_post_id'].'">'.format_time($cur_search['last_post']).'</a> <span class="byuser">'.$lang_common['by'].' '.DBC_htmlspecialchars($cur_search['last_poster']) ?></span></td>
				</tr>
<?php

			}
		}

		if ($show_as == 'topics')
			echo "\t\t\t".'</tbody>'."\n\t\t\t".'</table>'."\n\t\t".'</div>'."\n\t".'</div>'."\n".'</div>'."\n\n";

?>




<table width="100%" height="23" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="30" class="bg_forum_bott_left"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_bott_center"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="center" width="30" class="bg_forum_bott_right"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
</tr></thead></table>

<div class="<?php echo ($show_as == 'topics') ? 'linksb' : 'postlinksb'; ?>">
	<div class="inbox2">
		<p class="pagelink"><span class="contacts"><?php echo $paging_links ?></span></p>


		<div class="clearer"></div>
	</div>
</div>




<?php

		$footer_style = 'search';
		require DBC_ROOT.'engine/footer.php';
	}
	else
		message($lang_search['No hits']);
}


$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $lang_search['Search']);
$focus_element = array('search', 'keywords');
define('DBC_ACTIVE_PAGE', 'search');
require DBC_ROOT.'engine/engine.php';

?>

<table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="28" class="bg_forum_title_left"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $lang_search['Search'] ?></span></td>
<td align="center" width="28" class="bg_forum_title_right"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
</tr></table>



<table class="forum_adv_table"  width="100%" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" class="forum_adv_tleft" width="2"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="left" width="100%"><br/><div class="forum_adv">

		<form id="search" method="get" action="search.php">
					<div class="login_info"><?php echo $lang_search['Search criteria legend'] ?></div>
						<div class="infldset">
							<input type="hidden" name="action" value="search" />
							<label class="conl"><?php echo $lang_search['Keyword search'] ?><br /><input type="text" class="input_text"  name="keywords" size="40" maxlength="100" /><br /></label>
							<label class="conl"><?php echo $lang_search['Author search'] ?><br /><input id="author" class="input_text"  type="text" name="author" size="25" maxlength="25" /><br /></label>
							<p class="clearb"><?php echo $lang_search['Search info'] ?></p>
						</div>

					<div class="login_info"><?php echo $lang_search['Search in legend'] ?></div>
					<div class="infldset">
						<label class="conl"><?php echo $lang_search['Forum search']."\n" ?>
						<br /><select id="forum" name="forum">
<?php

if ($DBC_config['o_search_all_forums'] == '1' || $DBC_user['is_admmod'])
	echo "\t\t\t\t\t\t\t".'<option value="-1">'.$lang_search['All forums'].'</option>'."\n";

$result = $db->query('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.redirect_url FROM '.$db->prefix.'categories AS c INNER JOIN '.$db->prefix.'forums AS f ON c.id=f.cat_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.redirect_url IS NULL ORDER BY c.disp_position, c.id, f.disp_position', true) or error('Unable to fetch category/forum list', __FILE__, __LINE__, $db->error());

$cur_category = 0;
while ($cur_forum = $db->fetch_assoc($result))
{
	if ($cur_forum['cid'] != $cur_category) // A new category since last iteration?
	{
		if ($cur_category)
			echo "\t\t\t\t\t\t\t".'</optgroup>'."\n";

		echo "\t\t\t\t\t\t\t".'<optgroup label="'.DBC_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
		$cur_category = $cur_forum['cid'];
	}

	echo "\t\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'">'.DBC_htmlspecialchars($cur_forum['forum_name']).'</option>'."\n";
}

?>
							</optgroup>
						</select>
						<br /></label>
						<label class="conl"><?php echo $lang_search['Search in']."\n" ?>
						<br /><select id="search_in" name="search_in">
							<option value="all"><?php echo $lang_search['Message and subject'] ?></option>
							<option value="message"><?php echo $lang_search['Message only'] ?></option>
							<option value="topic"><?php echo $lang_search['Topic only'] ?></option>
						</select>
						<br /></label>
						<p class="clearb"><?php echo $lang_search['Search in info'] ?></p>
					</div>


					<div class="login_info"><?php echo $lang_search['Search results legend'] ?></div>
					<div class="infldset">
						<label class="conl"><?php echo $lang_search['Sort by']."\n" ?>
						<br /><select name="sort_by">
							<option value="0"><?php echo $lang_search['Sort by post time'] ?></option>
							<option value="1"><?php echo $lang_search['Sort by author'] ?></option>
							<option value="2"><?php echo $lang_search['Sort by subject'] ?></option>
							<option value="3"><?php echo $lang_search['Sort by forum'] ?></option>
						</select>
						<br /></label>
						<label class="conl"><?php echo $lang_search['Sort order']."\n" ?>
						<br /><select name="sort_dir">
							<option value="DESC"><?php echo $lang_search['Descending'] ?></option>
							<option value="ASC"><?php echo $lang_search['Ascending'] ?></option>
						</select>
						<br /></label>
						<label class="conl"><?php echo $lang_search['Show as']."\n" ?>
						<br /><select name="show_as">
							<option value="posts"><?php echo $lang_search['Show as posts'] ?></option>
							<option value="topics"><?php echo $lang_search['Show as topics'] ?></option>
						</select>
						<br /></label>
						<p class="clearb"><?php echo $lang_search['Search results info'] ?></p>
					</div>
			<p class="buttons"><input class="fbutton" type="submit" name="search" value="<?php echo $lang_common['Submit'] ?>" accesskey="s" /></p>
		</form>





<br/>
</div></td>
<td align="left" class="forum_adv_tright" width="2"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
</td></tr></table>
<table width="100%" height="23" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="30" class="bg_forum_bott_left"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_bott_center"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
<td align="center" width="30" class="bg_forum_bott_right"><img src="<?php echo $DBC_config['o_base_url'] ?>/engine/skins/images/spacer.gif" border="0"></td>
</tr></thead></table>

<?php
$footer_style = 'search';
require DBC_ROOT.'engine/footer.php';
